package leetcode.code1509;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int minDifference(int[] nums) {
		if (nums.length < 5) {
			return 0;
		}
		Map<Integer, Integer> counter = new HashMap<>();
		for (int num : nums) {
			counter.put(num, counter.getOrDefault(num, 0) + 1);
		}
		int p = 0, size = counter.size();
		int[] numbers = new int[size];
		for (int key : counter.keySet()) {
			numbers[p++] = key;
		}
		Arrays.sort(numbers);
		int ans = Integer.MAX_VALUE;
		for (int i = 0; i <= 3; i++) {
			int time = i;
			p = 0;
			while (time > 0) {
				int cnt = counter.get(numbers[p]);
				if (time >= cnt) {
					p++;
				}
				time -= cnt;
			}
			int min = numbers[p];
			time = 3 - i;
			p = numbers.length - 1;
			while (time > 0) {
				int cnt = counter.get(numbers[p]);
				if (time >= cnt) {
					p--;
				}
				time -= cnt;
			}
			int max = numbers[p];
			ans = Math.min(ans, max - min);
		}
		for (int i = 1; i < numbers.length; i++) {
			if (nums.length - counter.get(numbers[i - 1]) - counter.get(numbers[i]) <= 3) {
				if (numbers[i] - numbers[i - 1] < ans) {
					ans = numbers[i] - numbers[i - 1];
				}
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(718, this.minDifference(H.str2array3(
				"[448,433,498,103,81,537,995,376,286,737,132,702,740,446,811,709,578,534,821,730,216,1,344,192,645]")));
//		H.compare(0, this.minDifference(H.str2array3("[5,3,2,4]")));
//		H.compare(1, this.minDifference(H.str2array3("[1,5,0,10,14]")));
//		H.compare(0, this.minDifference(H.str2array3("[3,100,20]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
